package com.yc.spring.aop.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/2
 * Email haijunzhou@hnit.edu.cn
 */

// 基于接口实现
public class JDKProxy {

    public static void main(String[] args) {
        人 person = new 房东();
        人 proxyObject = proxy(person);
        proxyObject.say();
    }


    public static <E> E proxy(E target){
        Object proxyObject = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy,  // 代理对象
                                         Method method, // 方法对象
                                         Object[] args) // 参数数组
                            throws Throwable {
                        try {
                            System.out.println("前置增强");
                            Object ret = method.invoke(target, args);
                            System.out.println("返回增强");
                            return ret;
                        } catch (Exception e) {
                            System.out.println("异常增强");
                            throw new RuntimeException(e);
                        } finally {
                            System.out.println("后置增强");
                        }
                    }
                }
        );
        return (E) proxyObject;
    }



}
